package top.mcwebsite.playandroid.business.qa.ui

import android.os.Parcelable
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.accompanist.web.WebView
import com.google.accompanist.web.rememberWebViewStateWithHTMLData
import top.mcwebsite.playandroid.business.articles.api.model.ArticleModel
import top.mcwebsite.playandroid.business.qa.model.QAReplayComment
import top.mcwebsite.playandroid.business.qa.vm.QADetailIntent
import top.mcwebsite.playandroid.business.qa.vm.QADetailUiEffect
import top.mcwebsite.playandroid.business.qa.vm.QADetailViewModel
import kotlin.collections.ArrayList
import top.mcwebsite.lib.route.api.EasyRouter
import top.mcwebsite.lib.router.annotation.Param
import top.mcwebsite.lib.router.annotation.Route
import top.mcwebsite.playandroid.common.constant.RouteConfig
import top.mcwebsite.playandroid.common.constant.RouteConfig.Answer
import top.mcwebsite.playandroid.common.constant.RouteConfig.QADetail

@Route("${QADetail.PATH}/{${QADetail.Param.QA_ID}}")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun QADetailPage(
    @Param(name = QADetail.Param.QA_ID) qaId: Long,
    @Param(name = QADetail.Param.ARTICLE) articleModel: ArticleModel,
) {
    val viewModel: QADetailViewModel = viewModel()
    viewModel.HandleUiEffect {
        when (it) {
            is QADetailUiEffect.GoAnswerPagerUiEffect -> {
                EasyRouter.navigate("${Answer.PATH}/${qaId}/${it.index}?${Answer.Param.QUESTION}=${articleModel.title}") {
                    withParcelableArrayList("comments", viewModel.uiState.replayComments as ArrayList<out Parcelable>)
                }
            }
            is QADetailUiEffect.BackUiEffect -> {
                EasyRouter.popBackStack()
            }

        }
    }
    LaunchedEffect(key1 = qaId) {
        viewModel.sendIntent(QADetailIntent.InitQADetailIntent(qaId))
    }
    Scaffold(
        topBar = {
            TopAppBar(
                title = {},
                navigationIcon = {
                    IconButton(onClick = {
                        viewModel.sendIntent(QADetailIntent.BackIntent)
                    }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null)
                    }
                }
            )
        }
    ) {
        val uiState by viewModel.uiStateFlow.collectAsState()
        LazyColumn(
            modifier = Modifier.padding(it),
        ) {
            item {
                Text(
                    text = articleModel.title,
                    style = MaterialTheme.typography.titleLarge,
                    modifier = Modifier.padding(horizontal = 16.dp)
                )
                Box(modifier = Modifier.padding(horizontal = 16.dp)) {
                    WebView(state = rememberWebViewStateWithHTMLData(data = articleModel.desc))
                }
                Divider(
                    Modifier
                        .padding(horizontal = 16.dp)
                        .padding(bottom = 10.dp, top = 15.dp)
                )

            }

            items(uiState.replayComments.size) { index ->
                AnswerItem(replayComment = uiState.replayComments[index]) {
                    viewModel.sendIntent(QADetailIntent.ClickAnswerItemIntent(index))
                }
                if (index < uiState.replayComments.size - 1) {
                    Divider(modifier = Modifier.padding(vertical = 5.dp, horizontal = 16.dp))
                }
            }

            item {
                Spacer(modifier = Modifier.height(50.dp))
            }

        }
    }
}

@Composable
fun AnswerItem(replayComment: QAReplayComment, onClick: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .clickable {
                onClick.invoke()
            }
    ) {
        Text(text = replayComment.getDisplayUsername(), style = MaterialTheme.typography.titleMedium)
        Text(
            text = replayComment.contentMd,
            style = MaterialTheme.typography.bodyMedium,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.padding(vertical = 5.dp),
        )
        Row {
            Text(text = replayComment.getTips(), style = MaterialTheme.typography.labelMedium)
            Spacer(modifier = Modifier.weight(1f))
            Text(text = replayComment.niceDate, style = MaterialTheme.typography.labelMedium)
        }
    }
}

fun QAReplayComment.getTips(): String {
    val replayCountTips = if (replyComments.isNotEmpty()) {
        "${replyComments.size} 评论"
    } else null
    val zanCountTips = if (zan > 0) {
        "${zan} 点赞"
    } else null
    return listOf(replayCountTips, zanCountTips).filter { !it.isNullOrEmpty() }
        .joinToString(" · ")
}